import { defineEventHandler, readBody, setResponseStatus, send } from 'h3'
import redis from '../util/redis'

// POST /api/scoreboard  创建/更新一局数据
export default defineEventHandler(async (event) => {
  if (event.method !== 'POST') {
    setResponseStatus(event, 405)
    return send(event, 'Method Not Allowed')
  }
  try {
    const data = await readBody(event)
    if (!data.redisKey) throw new Error('缺少redisKey')
    await redis.set('scoreboard:' + data.redisKey, JSON.stringify(data), 'EX', 60 * 60 * 24 * 7) // 7天
    return { code: 0, msg: 'ok' }
  } catch (e) {
    setResponseStatus(event, 400)
    return { code: 1, msg: typeof e === 'object' && e && 'message' in e ? (e as any).message : String(e) }
  }
})
